#include "base/core/os/dynamic_lib.h"
#include "base/core/os/os_head.h"
#include <stdio.h>
#include "base/core/os/debug.h"
#include "base/core/com_define.h"
#include <string.h>

DynamicLib::DynamicLib() 
{
	handle_ = NULL;
}

DynamicLib::~DynamicLib() 
{
	if (handle_) 
	{
		FreeLibrary(handle_);    
	}
	handle_ = NULL;
}

int DynamicLib::Open(const char* dll_file) 
{
	if (handle_) 
	{
		FreeLibrary(handle_);
		handle_ = NULL;
	}

	handle_ = LoadLibrary(dll_file);
	if (handle_ == NULL) 
	{
		char errmsg[1024];
		OutputFmtToConsole("file:%s,LoadLibrary err: %s\n",
						dll_file,
						ErrorMsg(ErrorNO(), errmsg, sizeof(errmsg)));
	}
	MMO_ASSERT(handle_);
	return 0;
}

void* DynamicLib::Func(const char* func_name) 
{
	if (handle_ == NULL) 
	{
		OutputFmtToConsole("get func %s but handle is null\n", func_name);
		return NULL;
	}
	void* ret = GetProcAddress(handle_, func_name);
	if (ret == NULL)
	{
		char errmsg[1024];
		OutputFmtToConsole("get funcname:%s,LoadLibrary err: %s\n",
						func_name,
						ErrorMsg(ErrorNO(), errmsg, sizeof(errmsg)));
	}
	return ret;
}

